import csv
import time
from datetime import datetime
from common import file_mgmt
from f10 import f10_processor
from f10a import f10a_processor
from f10b import f10b_processor






# get today's raw data
def run(hq, max_retry=3,g_path = '/home/ubuntu/f10_serverside/'):

    print('--------Fetching f10 ---------')
    start_time = time.time()

    p = []
    # 1 最新提示 4 股东研究
    for code in hq.infoParamMap:
        p.append((code, "1"))
        p.append((code, "4"))
    res = hq.getInfo(p,{'1': '最新提示', '4': '股东研究'},max_retry)

    with open(g_path + 'f10/res/res_' + datetime.today().strftime('%Y-%m-%d') + '.csv', 'w', newline='',
              encoding="utf-8-sig",
              errors="ignore") as csvfile:
        fieldnames = ['code', 'content', 'flag']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()
        for i in res:
            try:
                writer.writerow(i)
            except Exception as x:
                print('Error occurred when writing f10 res.')
                print(str(x))

    print("--------------------- f10 res fetched  --------------------")
    res.clear()
    u = file_mgmt.push(dir=g_path + "f10/res")
    if u[1]:
        f10_processor.run(u[1], g_path+'f10/')
        print("--------------------- f10 bin saved  --------------------")
        print("--------------------- starting f10a  --------------------")
        f10a_processor.run(u[1], g_path+'f10a/')
        f10b_processor.run(u[1], g_path+'f10b/')
    end_time = time.time()
    hours, rem = divmod(end_time - start_time, 3600)
    minutes, seconds = divmod(rem, 60)
    print("-------- f10 & f10a finished and cost {:0>2}:{:0>2}:{:05.2f}. -------".format(
        int(hours), int(minutes), seconds))


if __name__ == '__main__':
    run()
